﻿using UnityEngine;
using System.Collections;

namespace TCG
{
	/// <summary>
	/// 游戏运行时资源数据库，单例。
	/// </summary>

	public class GameAssetsDatabase : MonoBehaviour 
	{
		public static GameAssetsDatabase m_instance = null;

		public static GameAssetsDatabase instance
		{
			get 
			{
				if (m_instance == null)
				{
					GameObject go = new GameObject ();
					go.name = "_TCG_GameAssetsDatabase";
					GameObject.DontDestroyOnLoad (go);
					m_instance = go.AddComponent<GameAssetsDatabase> ();
				}
				return m_instance;
			}
		}

		void Awake ()
		{
			m_textureDatabase = gameObject.AddComponent<GameTextureDatabase> ();
			m_materialDatabase = gameObject.AddComponent<GameMaterialDatabase> ();
			m_prefabDatabase = gameObject.AddComponent<GamePrefabDatabase> ();
			m_assetLoader = gameObject.AddComponent<GameAssetsLoader> ();
		}

		public void Initialize (System.Action callback)
		{
			StartCoroutine (Co_Initialize (callback));
		}

		public void UnloadUnusedAssets ()
		{
			m_prefabDatabase.UnloadUnusedAssets ();
			m_materialDatabase.UnloadUnusedAssets ();
			m_textureDatabase.UnloadUnusedAssets ();
		}

		public GameTextureDatabase textureDatabase { get { return m_textureDatabase;} }

		public GameMaterialDatabase materialDatabase { get {  return m_materialDatabase; } }

		public GamePrefabDatabase prefabDatabase { get { return m_prefabDatabase; } }

		public GameAssetsLoader assetLoader { get { return m_assetLoader; } }

		IEnumerator Co_Initialize (System.Action callback)
		{
            yield return null;
            assetLoader.Initialize ();
            yield return null;
            textureDatabase.Initialize (assetLoader);
			yield return null;
            materialDatabase.Initialize (assetLoader);
			yield return null;
            prefabDatabase.Initialize (assetLoader);
			yield return null;
			callback ();
		}

		GameTextureDatabase m_textureDatabase = null;

		GameMaterialDatabase m_materialDatabase = null;

		GamePrefabDatabase m_prefabDatabase = null;

		GameAssetsLoader m_assetLoader = null;
	}
}
